package root.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.log4j.Logger;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import root.service.LoginService;
import root.utils.DesUtils;
import root.utils.StringHelper;
import root.utils.WebConstants;

import javax.servlet.http.Cookie;
import javax.sound.midi.Soundbank;
import java.util.Date;

/**
 * 用户操作类的控制器
 */
public class UserInterceptor implements Interceptor {

    private LoginService loginService = new LoginService();

    //拦截是否登录
    public void intercept(Invocation inv) {
        String cookie = inv.getController().getCookie(WebConstants.MANAGER_USER);
        if(StringHelper.isEmpty(cookie)){
            inv.getController().renderJson(errorMsg(-1,"登录信息失效"));
            return ;
        }
        try {
            DesUtils desUtils = new DesUtils();
            String decrypt = desUtils.decrypt(cookie);
            String[] split = decrypt.split("_");
            if(split.length!=2){
                inv.getController().renderJson(errorMsg(-1,"登录信息失效"));
                return ;
            }
            Record loginUser = loginService.checkLoginInfo(split[0],split[1]);
            if(loginUser == null){
                inv.getController().renderJson(errorMsg(-1,"登录信息失效"));
                return ;
            }
            inv.getController().setAttr(WebConstants.USERID,loginUser.getInt("id"));
            inv.getController().setAttr(WebConstants.USERNAME,loginUser.getStr("realname"));
            inv.getController().setAttr(WebConstants.MOBILEPHONE,loginUser.getStr("phone"));
            Date date = new Date();
            inv.invoke();
            System.out.println("请求耗时："+ (new Date().getTime()-date.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
            inv.getController().renderJson(errorMsg(1,"系统错误"));
        }
    }

    private JSONObject errorMsg(int code, String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        return jsonObject;
    }

}
